package com.example.administrator.accessabilityservicestudy;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TimeUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private EditText et_content;
    private Button bt_save, bt_clear;
    public static String MM = "com.tencent.mm";
    public ListView listView;
    private MyAdapter adapter;
    List<DataBean> datas = new ArrayList<>();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:

                    bt_clear.performClick();
                    break;

            }

        }
    };
    int count = 0;

    String folderName = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_content = (EditText) findViewById(R.id.et_content);
        bt_save = (Button) findViewById(R.id.bt_save);
        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                folderName = "CameraImage"+System.currentTimeMillis();
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                intent.putExtra("foldername",folderName);
                startActivityForResult(intent, 100);

            }
        });
        bt_clear = (Button) findViewById(R.id.bt_clear);
        bt_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (datas.size() <= 0) {
                   Toast.makeText(MainActivity.this,"请添加发送内容",Toast.LENGTH_SHORT).show();
                }
                AutoSendServiece.CONTENT = datas.get(count).getContent();
                AutoSendServiece.LIST_FILE = datas.get(count).getFilePath();
                AutoSendServiece.folderName = datas.get(count).getFolderName();
                if (datas.get(0).getFilePath() != null && datas.get(count).getFilePath().size() > 0) {
                    AutoSendServiece.IS_FILE = true;
                }

                ComponentName componet = new ComponentName(MM, "com.tencent.mm.ui.LauncherUI");
                //pkg 就是第三方应用的包名
                //cls 就是第三方应用的进入的第一个Activity
                Intent intent = new Intent();
                intent.setComponent(componet);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                AutoSendServiece.ACTIVE = true;
                AutoSendServiece.FirstCheck = true;

                count++;
                if(count<datas.size()) {
                    handler.sendEmptyMessageDelayed(1, 1000 * 20);
                }


            }
        });

        listView = (ListView) findViewById(R.id.listview);
        adapter = new MyAdapter(this, datas);
        listView.setAdapter(adapter);
    }

    private void doStartApplicationWithPackageName(String packagename) {

        // 通过包名获取此APP详细信息，包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List<ResolveInfo> resolveinfoList = getPackageManager()
                .queryIntentActivities(resolveIntent, 0);

        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式：packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            // LAUNCHER Intent
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            // 设置ComponentName参数1:packagename参数2:MainActivity路径
            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            startActivity(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 200 && data != null) {
            Bundle bundle = data.getExtras();
            String content = bundle.getString("content");
            String folderName = bundle.getString("folername");
            List<LocalMedia> filePaths = data.getParcelableArrayListExtra("filePath");
            if (!TextUtils.isEmpty(content) || (filePaths != null && filePaths.size() > 0)) {
                DataBean dataBean = new DataBean(content, filePaths,folderName);
                datas.add(dataBean);
                adapter.notifyDataSetChanged();
            }
        }
    }
}
